<?php

ini_set("display_errors", "On");
error_reporting(E_ALL | E_STRICT);

date_default_timezone_set("Asia/Shanghai");

session_start();

define("UTILS_AUTOLOADER_PATH", dirname(__FILE__));
define("MD_DIR", './md');
$category_path = "./main.md";

function init(){
    spl_autoload_register('autoload');
}

/**
 * 类库自动加载，写死路径，确保不加载其他文件。
 * @param string $class 对象类名
 * @return void
 */
function autoload($class) {
    $file = preg_replace('{\\\\|_(?!.*\\\\)}',
            DIRECTORY_SEPARATOR,
            trim($class, '\\')) . '.php';
    $file = UTILS_AUTOLOADER_PATH . "/libs/" . $file;
    if(is_file($file)){
        include $file;
        return;
    }

}

init();

//根据page_doc里的main.md，获取目录
/*
 格式是：
intro ### 1 平台介绍
manual ### 2 平台使用说明
server ### 3 服务端API
android_sdk ### 4 安卓端SDK
protocol ### 5 用户协议

intro就是intro.md
1 平台介绍 就是左边sidebar的目录名字
 */


//页面中如果有"[链接]"这种文本，就处理成超链接，指向其他wiki页面
function wikiLinks($page){
    if(preg_match_all('/\[([^\]]+?)\]/', $page, $matches, PREG_SET_ORDER)){
        foreach ($matches as $match){
            $href = '<a href="{url}">{title}</a>';
            $href = str_replace("{url}",
                $_SERVER["SCRIPT_NAME"] . "?page=" . urlencode($match[1]),
                $href);
            $href = str_replace("{title}", htmlentities($match[1]), $href);
            $page = str_replace($match[0], $href, $page);
        }
    }
    return $page;
}

function getDocs($file_path){
    $docs = array();
    if(file_exists($file_path)){
        $fp = fopen($file_path,"r");
        $str ="";
        while(!feof($fp)){
            $str = fgets($fp);//逐行读取。如果fgets不写length参数，默认是读取1k。
            if(trim($str) != ''){
                $parts = explode("###", trim($str));
                $doc_name = trim($parts[0]);
                $doc_title = trim($parts[1]);
                $doc_type = trim($parts[2]);
                $docs[] = array("name" => $doc_name, "title" => $doc_title, "type" => $doc_type);
            }
        }
        fclose($fp);
    }

    return $docs;
}

$docs = getDocs($category_path);
//print_r($docs);


$current_name = '';
$current = null;
if(isset($_GET['r'])){
    $current_name = $_GET['r'];
}else{
    $current_name = $docs[0]['name'];
}

foreach ($docs as $doc){
    if($doc['name'] == $current_name){
        $current = $doc;
    }
}

?>


<html>
        <head>
            <meta charset="utf-8" />
            <title><?php echo $current['title'] ?></title>
                <meta name="description" content="一点儿都不酷">
            <link rel="stylesheet" href="./assets/css/bootstrap.min.css?v=1.2" />
            <!-- <link rel="stylesheet" href="/Public/css/flat-ui.min.css" /> -->
            <link rel="stylesheet" href="./assets/css/main.css?v=1.4" />
            <link rel="shortcut icon" href="./assets/favorite.png" type="image/x-icon" />
        </head>
        
        <body>
            <div class="hd">
                <div class="wrapper">
                </div>
            </div>
            <div class="main main-doc  ">
        
                <div class="wrapper">
                    <div class="doc-cat">


                        <div class="doc-cat-item">
                            <span class="doc-cat-title">文档</span>
                            <ul>
                                <?php
                                    foreach ($docs as $doc){
                                        $class = "";
                                        if($doc['name'] == $current_name){
                                            $class = 'active';
                                        }

                                        $str = "<li class='$class'><a href='./index.php?r={$doc['name']}'>{$doc['title']}</a></li>";
                                        echo $str;
                                    }

                                ?>

                            </ul>
                        </div>        </div>

            <div class="doc-ctn">
                <h1><?php echo $current['title']?></h1>

                <?php

                $filepath = MD_DIR . "/" . $current['name'] . ".md";
                if(file_exists($category_path)){
                    $text = file_get_contents($filepath);
                    if($current['type'] == 'md'){

                        $parser = new HyperDown\Parser;
                        $text = $parser->makeHtml($text);

//                        $text = \Michelf\Markdown::defaultTransform($text);
                        //使[links]连接到其他wiki页面
                        $text = wikiLinks($text);
                    }else{
                        ///html
                        /// 不需要处理什么了
                    }
                    echo $text;
                }

                ?>
            </div>
            </div>
            <div class="clear"></div>
            <div id="fill"></div>
            </div>

        <div class="ft">
         </div>
        
        <script src="./assets/jquery-1.11.3.min.js"></script>
        <script src="./assets/js/bootstrap.min.js?v=1.2"></script>
        <script type="text/javascript">
        
          $('[data-toggle="tooltip"]').tooltip()
        
            var fillPadding = function() {
                $('#fill').height($('#fill').height() + window.innerHeight - ($('.main').offset().top + $('.main').height() + $('.ft').height()))
            }
            $(window).resize(fillPadding);
            fillPadding();
            $('.ft').show();
        </script>
        

        </body>
        </html>